/*global ethereum*/
import { useState, useMemo, useEffect } from 'react';
import MetaMaskOnboarding from '@metamask/onboarding'

function App() {
  const isMetaMaskInstalled = useMemo(() => {
    const { ethereum } = window;
    return Boolean(ethereum && ethereum.isMetaMask);
  }, [])
  const [balance, setBalance] = useState('undefined')
  const [onboarding] = useState(() => {
    const forwarderOrigin = 'http://localhost:3001'
    return new MetaMaskOnboarding({ forwarderOrigin });
  })
  const [isInstalling, setIsInstalling] = useState(false)
  function handleClickInstall() {
    setIsInstalling(true)
    onboarding.startOnboarding();
  }
  async function handleClickConnect() {
    try {
      // Will open the MetaMask UI
      // You should disable this button while the request is pending!
      await ethereum.request({ method: 'eth_requestAccounts' });
    } catch (error) {
      console.error(error);
    }
  };
  async function handleGetBalance() {
    const _accounts = await ethereum.request({ method: 'eth_accounts' });
      //We take the first address in the array of addresses and display it
    console.log('_accounts', _accounts)
    const _balance = await ethereum.request({ method: 'eth_getBalance', params: [_accounts[0], 'latest'] });
    console.log('_balance', _balance)

    setBalance(_balance[0] || 'Not able to get accounts')
  }
  useEffect(() => {
    if (window.ethereum) {
      ethereum.on('chainChanged', function (chainId) {
        // if the chainId did not match Polygon ,show warning
        if (chainId !== '0x89') {
          console.warn('the network is wrong')
        }
      });
    }
    return () => {
      // off the event
    }
  }, [])
  return (
    <div className="App">
      {
        isInstalling && <button disabled={true}>Onboarding in progress</button>
      }
      {
        (!isInstalling && isMetaMaskInstalled) ? (<button onClick={handleClickConnect}>Connect</button>) : (<button onClick={handleClickInstall}>Click here to install MetaMask!</button>)
      }
      <button onClick={handleGetBalance}>getBalance</button>
      <div>result: {balance}</div>
    </div>
  );
}

export default App;
